package dk.lector.service;

import java.util.Calendar;

import dk.lector.R;
import dk.lector.datasource.DocDBRepository;
import dk.lector.datasource.UserDBRepository;
import dk.lector.domain.TSSystemIntent;
import dk.lector.domain.TeamShareMobile;
import dk.lector.domain.entities.User;
import dk.lector.exception.ExceptionHandler;
import dk.lector.providers.CACHEDDOC_VIEWContentProvider;
import dk.lector.utils.FileSystemUtil;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.util.Log;

public class CleanupService extends Service {

	private static final String TAG = CleanupService.class.getSimpleName();
	private static String EXTRA_INTERVAL_KEY, EXTRA_TARGET_KEY,
			EXTRA_TARGET_DOCS, EXTRA_TARGET_USER;
	private static int DEFAULT_INTERVAL;
	private static int minutesToKeepDocuments, minutesToKeepUser;
	private String[] workDone;

	@Override
	public void onCreate() {
		super.onCreate();
		Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));
		workDone = new String[]{"",""};
		
		EXTRA_INTERVAL_KEY = CleanupServiceHelper.EXTRA_INTERVAL_KEY;
		EXTRA_TARGET_KEY = CleanupServiceHelper.EXTRA_TARGET_KEY;
		EXTRA_TARGET_DOCS = CleanupServiceHelper.EXTRA_TARGET_DOCS;
		EXTRA_TARGET_USER = CleanupServiceHelper.EXTRA_TARGET_USER;
		DEFAULT_INTERVAL = CleanupServiceHelper.DEFINED_ALARM_DEFAULT_INTERVAL;
		Log.d(TAG, "onCreate'd");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.d(TAG, "onStart'd with action: " + " " + intent.getAction());
		TeamShareMobile core = (TeamShareMobile) getApplicationContext();

		if (intent.getAction().equals(R.string.ACTION_START_CLEANUP_SERVICE)) {
			if (intent.getStringExtra(EXTRA_TARGET_KEY).equals(
					EXTRA_TARGET_DOCS)) {
				Log.d(TAG, "running docClean");
				minutesToKeepDocuments = intent.getIntExtra(EXTRA_INTERVAL_KEY,
						DEFAULT_INTERVAL);
				runDocClean(core);
				workDone[0] = "Doc cleanup";
				return;
			} else if (intent.getStringExtra(EXTRA_TARGET_KEY).equals(
					EXTRA_TARGET_USER)) {
				Log.d(TAG, "running userClean");
				minutesToKeepUser = intent.getIntExtra(EXTRA_INTERVAL_KEY,
						DEFAULT_INTERVAL);
				runUserClean(core);
				workDone[1] = "user cleanup";
				return;
			}

		}
		onDestroy();
	}

	private static void runUserClean(TeamShareMobile core) {
		long milisToKeepUser = minutesToKeepUser * 60000;
		long now = Calendar.getInstance().getTimeInMillis();

		User user = core.getUser();
		long lastActive = user.getTimestampActivity();

		if ((now - lastActive) < milisToKeepUser) {
			UserDBRepository.deleteUser(core);
		}
	}

	private static void runDocClean(Context context) {
		long milisToKeepDocuments = minutesToKeepDocuments * 60000;
		long now = Calendar.getInstance().getTimeInMillis();

		Cursor c = DocDBRepository.getLocalDocuments(context);
		c.moveToFirst();
		while (!c.isAfterLast()) {
			long lastActive = c.getLong(c.getColumnIndex(CACHEDDOC_VIEWContentProvider.TIMESTAMP_ACTIVITY));
			
			if ((now - lastActive) < milisToKeepDocuments) {
				FileSystemUtil.deleteSingleFile(
						c.getString(c.getColumnIndex(CACHEDDOC_VIEWContentProvider.FILE_PATH)),
						context);
				DocDBRepository.deleteDocument(context,
						c.getInt(c.getColumnIndex(CACHEDDOC_VIEWContentProvider._ID)));
			}
			c.moveToNext();
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		
		if(workDone[0] != "" && workDone[1]!="")
		sendBroadcast(new TSSystemIntent(R.string.ACTIONCODE_CLEAN_UP_DONE, TAG));
		Log.d(TAG, "onDestroy'd, the service has run: " + workDone[0] + " " + workDone[1]);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

}
